<template>
  <div class="page-container page-footer-btn">
    <FortenScan
        ref="scanDom"
        propPlaceholder="扫描条码"
        propErrorMsg="扫描条码"
        @scanCall="handleScanOver"
        v-if="form.deptIdFrom && form.id"
      />
    <van-form >
      <div class="items-container">
        <van-row v-if="strings.isBlank(form.id)">
          <van-col span="24"><van-field is-link @click="showDeptPopup" left-icon="home-o" placeholder="请选择科室" label="退货科室" :value="form.deptNameFrom"></van-field></van-col>
        </van-row>
        <van-row v-if="strings.isBlank(form.id)">
          <van-col span="24"><van-field is-link @click="showWarehousePopup" left-icon="cart-o" placeholder="请选择目标仓库" label="目标仓库" :value="form.toWarehouseName"></van-field></van-col>
        </van-row>
        <van-row v-if="form.id">
          <van-col span="12"><van-icon name="home-o" size="15" color="#1989fa" style="top: 3px;"/> 退货科室</van-col>
          <van-col span="12"><van-icon name="cart-o" size="15" color="#1989fa" style="top: 3px;"/> 目标仓库</van-col>
        </van-row>
        <van-row v-if="form.id">
          <van-col span="12" class="list-value">{{form.deptNameFrom}}</van-col>
          <van-col span="12" class="list-value">{{form.toWarehouseName}}</van-col>
        </van-row>
        <van-row v-if="form.id">
          <van-col span="12"><van-icon name="label-o" size="15" color="#1989fa" style="top: 3px;"/> 退货单号</van-col>
          <van-col span="12"><van-icon name="after-sale" size="15" color="#1989fa" style="top: 3px;"/> 退货金额</van-col>
        </van-row>
        <van-row v-if="form.id">
          <van-col span="12" class="list-value">{{form.busKey}}</van-col>
          <van-col span="12" class="list-value">{{form.amount}}</van-col>
        </van-row>
      </div>
    </van-form>  
    <van-divider><span style="font-size:9px">退货单明细</span></van-divider>
    <div class="items-container">
      <stock-item
        v-for="item in formItems"
        :key="item.id"
        :item="item"
      />
    </div>

    <van-row type="flex" justify="space-around" class="footer-btn">
      <van-col span="5">
        <van-button  :disabled="form.id" text="创建"  type="primary" @click="handleCreate"></van-button>
      </van-col>
      <van-col span="5">
        <van-button  :disabled="!form.id" text="提交"  type="primary" @click="handleFlowButtonClick"></van-button>
      </van-col>
    </van-row>

    <!-- 选择仓库-->
    <FortenList ref="warehouseList" :propAutoFetchData = 'false'
      :propIsRadio="true"
      :propFlagPopup="true"
      :propSearchFields="['name']"
      :propSearchTextAppend="'仓库名字'"
      propUrl="/base/warehouse/getCenter"
      @change="warehouseCheck"
      :disabled="strings.isBlank(form.id)"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="5">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="20">{{item.name}}</van-col>
        </van-row>
      </template>
    </FortenList>
    <!-- 选择科室-->
    <FortenList ref="deptList" :propAutoFetchData = 'false'
      :propIsRadio="true"
      :propFlagPopup="true"
      :propSearchFields="['name']"
      :propSearchTextAppend="'科室名字'"
      propUrl="/base/dept/pageBusDept"
      @change="deptCheck"
      :disabled="strings.isBlank(form.id)"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="5">科室：</van-col>
          <van-col span="15">{{item.name}}</van-col>
        </van-row>
        <van-row >
          <van-col span="4">
          </van-col>
          <van-col span="5">二级仓库：</van-col>
          <van-col span="15">{{item.warehouseName}}</van-col>
        </van-row>
      </template>
    </FortenList>
    </div>
</template>

<script>

import { Button, Popup, Sticky, List, Image as VanImage, NumberKeyboard, DatetimePicker, Swipe, SwipeItem, RadioGroup, Radio, Checkbox, CheckboxGroup   } from 'vant'
import Vue from 'vue'
import FlowButtons from '@/components/FlowButtons.vue'
import ReturnItem from './DeptReturnItem.vue'
import barcodeParse from '@/util/barcodeParse.js'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(DatetimePicker)
Vue.use(VanImage)
Vue.use(NumberKeyboard)
Vue.use(List)
Vue.use(Popup)

export default {
  data() {
    return {
      form: {},
      formItems: {},
      images: [],
      searchedList: [],
      result: [],
      searchValue: '',
      scan: '',
      show: false,
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom.focus()
    this.getBaseData()
  },
  computed: {
  },
  methods: {
    getBaseData() {
      const currentUser = this.$store.getters.currentUser.currentUser
      this.$set(this.form, 'deptNameFrom', currentUser.deptName)
      this.$set(this.form, 'deptIdFrom', currentUser.deptId)
      this.getWarehouse()
    },
    getWarehouse() {
      this.$ajax.get('/base/warehouse/getCenter').then(resp => {
        if (resp.code == 0 && resp.data.length > 0) {
          this.$set(this.form, 'toWarehouseId', resp.data[0].id)
          this.$set(this.form, 'toWarehouseName', resp.data[0].name)
        }
      })
    },
    handleScanClear(event) {
      this.scan = ''
    },
    showDeptPopup() {
      this.$refs.deptList.show()
    },
    showWarehousePopup() {
      this.$refs.warehouseList.show()
    },
    handleScanOver(scanValue) {
      this.utils.loadShow()
      let prefix = scanValue.substring(0, 5)
      let codeType = ''
      if (prefix != 'trans') {
        codeType = barcodeParse.barCodeType(scanValue)
        if (codeType != 'SN' && codeType != 'RFID') {
          this.$notify.warning('请扫描有效的条码')
          this.utils.loadHide()
          this.utils.clearFocus(this, 'scanDom', 'scan')
          window.scanError()
          return
        }
        this.saveReturnItem(scanValue)
      } else {
        this.getDeptReturn(scanValue)
      }
      this.scan =  ''
    },
    saveReturnItem(code) {
      const params = {
        isScan: 1,
        transferId: this.form.id,
        uniqueCode: code,
        fromWarehouseId: this.form.fromWarehouseId,
      }
      this.$ajax.post('/wm/transfer_item/scan', params).then(resp => {
        if (resp.code == 0) {
          this.getDeptReturn(this.form.busKey)
        }

        this.utils.loadHide()
        this.utils.clearFocus(this, 'scanDom', 'scan')
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    getDeptReturn(scan) {
      const params = {
        busKey: scan
      }
      this.$ajax.get('/wm/transfer/getByBusKey', { params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.form = response.data.transfer || []
          this.formItems = response.data.transferItems || []
          this.form.qty = this.formItems.length || 0
        } else {
          this.$notify.error(response.msg)
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    async handleFlowButtonClick() {
      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: '确定要进行提交操作吗？'
      })
      if (!result) {
        return
      }
      this.utils.loadShow()
      let busId = ''
      busId = this.form.id
      const flowKey = this.propFlowKey.split(':')[0]
      let params = {
        flowKey: 'std_dept_return',
        buttonKey: 'submit',
        busId: this.form.id,
        flowStatusTextFrom: '拣货完成',
        flowStatusTextTo: '开始退库',
        busTable: 'wm_moving',
        busIdName: '调拨id',
        busTypeName: 'transfer/transfer-pick-fast'
      }
      this.$ajax.post('/wm/transfer/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.$notify.success('提交操作成功！')
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    clearForm() {
      this.form = {}
      this.formItems = []
      this.scan = ''
      this.$refs.scanDom.focus()
      this.getWarehouse()
    },
    deptCheck(item) {
      if (this.form.deptIdFrom == item.id) {
        this.show = false
        return
      }
      this.reDeptCheck(item)
    },
    warehouseCheck(item) {
      if (this.form.toWarehouseId == item.id) {
        this.show = false
        return
      }
      this.$set(this.form, 'toWarehouseId', item.id)
      this.$set(this.form, 'toWarehouseName', item.name)
    },
    reDeptCheck(item) {
      if (this.strings.isEmpty(item.warehouseId)) {
        this.$notify.warning('该科室并没有绑定相应的二级库，请联系管理员！')
        return
      }
      this.$set(this.form, 'fromWarehouseId', item.warehouseId)
      this.$set(this.form, 'fromWarehouseName', item.warehouseName)
      this.$set(this.form, 'deptIdFrom', item.id)
      this.$set(this.form, 'deptNameFrom', item.name)
      this.show = false
    },
    handleCreate() {
      if (this.form.id) {
        this.$dialog.confirm({
          message: '当前单据未提交，是否创建新单据?',
        }).then(() => {
          this._handleCreate()
        }).catch(() => {
          // on cancel
        })
      } else {
        this._handleCreate()
      }
    },
    _handleCreate() {
      if (!this.form.deptIdFrom) {
        this.$notify.error('请先选择退货科室！')
        return
      }
      if (!this.form.toWarehouseId) {
        this.$notify.error('请先选择退库的目标仓库！')
        return
      }
      this.utils.loadShow()
      const currentUser = this.$store.getters.currentUser.currentUser
      const params = {
        busDate: new Date().format('yyyy-MM-dd hh:mm:ss'),
        busUser: currentUser.name,
        deptIdFrom: this.form.deptIdFrom,
        deptNameFrom: this.form.deptNameFrom,
        fromWarehouseId: this.form.fromWarehouseId,
        fromWarehouseName: this.form.fromWarehouseName,
        toWarehouseId: this.form.toWarehouseId,
        toWarehouseName: this.form.toWarehouseName,
        type: 'returnIn'
      }
      this.$ajax.post('/wm/transfer/save', params).then(res => {
        if (res.code == 0) {
          this.form = res.data
          this.$notify.success('创建成功！')
        }
        this.utils.loadHide()
        this.utils.clearFocus(this, 'scanDom', 'scan')
      })
    }
  },
  components: {
    ReturnItem,
    FlowButtons,
    RadioGroup,
    Sticky,
    Checkbox,
    CheckboxGroup,
    Radio,
    Button
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .popup {
    width: 80%;
    height: 100%;
  }
  .footer{
    position: fixed;
    left: 0px;
    bottom: 0px;
    width: 100%;
    height: 50px;
  }
  .btn-container {
    margin-left: 1%;
    margin-right: 1%;
    flex-direction:column ;
    justify-content: space-between;
    display:inline-block;
    width: 80%;
  }
  .creat{
    margin-left: 1%;
    flex-direction:column ;
    justify-content: space-between;
  }
</style>
